package com.treasure.hunt.main

import android.widget.ImageView
import android.widget.LinearLayout
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.ConvertUtils
import com.blankj.utilcode.util.ScreenUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.module.lemlin.base.loadCropImage
import com.module.lemlin.base.loadRoundImage
import com.module.lemlin.mode.ViewModeFragment
import com.module.lemlin.rxhttp.Status
import com.module.lemlin.rxhttp.msg
import com.module.lemlin.util.AnimManager
import com.module.lemlin.util.qqShareImage
import com.module.lemlin.util.wxShareImage
import com.treasure.hunt.R
import com.treasure.hunt.app.AppConstance
import com.treasure.hunt.entity.*
import com.treasure.hunt.getDiskCacheDirectoryImage
import com.treasure.hunt.mine.MineInfoActivity
import com.treasure.hunt.mode.TaskViewMode
import com.treasure.hunt.popup.DialogFlopPopup
import com.treasure.hunt.popup.DialogSharePopup
import com.treasure.hunt.task.TaskFlopActivity
import com.treasure.hunt.task.TaskGridActivity
import com.treasure.hunt.task.TaskInviteActivity
import com.treasure.hunt.task.TaskLuckyActivity
import kotlinx.android.synthetic.main.fragment_main_task.*
import org.greenrobot.eventbus.EventBus
import rxhttp.RxHttp

class MainTaskFragment : ViewModeFragment<TaskViewMode>() {

    companion object {
        fun newInstance(): MainTaskFragment {
            return MainTaskFragment()
        }
    }

    private val flopPopup: DialogFlopPopup by lazy {
        DialogFlopPopup(context = requireContext(), onAnimationEnd = {

            if (it.tag as Boolean) {
                viewModel.taskSignList()
                return@DialogFlopPopup
            }

            if (it.drawable == null)
                return@DialogFlopPopup

            val mainBean: MainBean<Action, Any> = MainBean(
                type = Action.GO_MINE
            )
            EventBus.getDefault().post(mainBean)

            val circleImageView = ImageView(activity)
            val layoutParams = LinearLayout.LayoutParams(
                ConvertUtils.dp2px(50f), ConvertUtils.dp2px(50f)
            )
            circleImageView.layoutParams = layoutParams
            circleImageView.loadRoundImage(it.drawable, radius = 25)

            val animManager: AnimManager = AnimManager.Builder()
                .with(requireActivity())
                .animModule(AnimManager.AnimModule.BIG_CIRCLE)
                .time(1200)
                .listener(object : AnimManager.AnimListener {
                    override fun setAnimBegin(a: AnimManager) {}
                    override fun setAnimEnd(a: AnimManager) {
                        a.stopAnim()
                    }
                })
                .animView(circleImageView)
                .build()
            animManager.startAnim(
                intArrayOf(
                    (ScreenUtils.getAppScreenWidth() / 2) - ConvertUtils.dp2px(25f),
                    ScreenUtils.getAppScreenHeight() / 2
                ), intArrayOf(
                    ScreenUtils.getAppScreenWidth() / 8 * 7,
                    ScreenUtils.getAppScreenHeight()
                )
            )
        }, onDoubled = {
            val maps: MutableMap<String, Any?> = mutableMapOf(
                "advertisement_type" to 5,
                "luck_draw_type" to 7,
                "model_type" to 6,
                "reward_id" to it.id
            )
            viewModel.videoType(maps)
        })
    }

    private var shareType: Int = 1
    private val sharePopup: DialogSharePopup by lazy {
        DialogSharePopup(context = requireContext()) { view ->
            shareType = when (view.id) {
                R.id.tvDialogShareWX -> 1
                else -> 2
            }
            viewModel.otherShareImage(3)
        }
    }

    private val taskAdapter =
        object : BaseQuickAdapter<TaskDay, BaseViewHolder>(R.layout.item_task_day) {
            init {
                addChildClickViewIds(
                    R.id.tvTaskDayCompleteWith,
                    R.id.tvTaskDayCompleteWait,
                    R.id.ivTaskDayIcon
                )
            }

            override fun convert(holder: BaseViewHolder, item: TaskDay) {
                holder.setText(
                    R.id.tvTaskDayTitle,
                    "${item.title}(${item.completion_times}/${item.condition_num})"
                )
                    .setText(R.id.tvTaskDayTitleSub, item.subtitle)
                    .setText(R.id.tvTaskDayRewardName, item.reward_content.name)
                    .setGone(R.id.tvTaskDayCompleteWith, item.status != 1)
                    .setGone(R.id.tvTaskDayCompleteWait, item.status != 2)
                    .setGone(R.id.tvTaskDayCompleteAfter, item.status != 3)
                val isHttps: Boolean = item.image.substring(0, 5).contains("http") ||
                        item.image.substring(0, 5).contains("https")
                holder.getView<ImageView>(R.id.ivTaskDayIcon)
                    .loadCropImage("${if (isHttps) "" else AppConstance.URL_IMAGE}${item.image}")
                holder.getView<ImageView>(R.id.ivTaskDayRewardIcon)
                    .loadCropImage("${if (isHttps) "" else AppConstance.URL_IMAGE}${item.reward_content.image}")
            }
        }

    override val layoutResId: Int
        get() = R.layout.fragment_main_task

    override fun viewModel(): TaskViewMode {
        return createViewModel()
    }

    private fun taskDayCompleteWith(taskDay: TaskDay) {
        //"任务类型:1=视频,2=分享,3=召唤,4=翻牌,5=签到,6=大转盘,7=邀请好友,8=合成,,9=绑定微信,10=绑定QQ"
        when (taskDay.task_type) {
            1 -> {
                val maps: MutableMap<String, Any?> = mutableMapOf(
                    "advertisement_type" to 5,
                    "luck_draw_type" to 5,
                    "task_id" to taskDay.id
                )
                viewModel.videoType(maps)
            }
            2 -> {
                sharePopup.showPopupWindow()
            }
            3 -> {
                val mainBean: MainBean<Action, Any> = MainBean(
                    type = Action.GO_HUNT
                )
                EventBus.getDefault().post(mainBean)
            }
            4 -> {
                TaskFlopActivity.open(requireActivity())
            }
            5 -> {
                viewModel.taskSignList()
            }
            6 -> {
                TaskGridActivity.open(requireActivity())
            }
            7 -> {
                TaskInviteActivity.open(requireActivity())
            }
            8 -> {
                val mainBean: MainBean<Action, Any> = MainBean(
                    type = Action.GO_HOME
                )
                EventBus.getDefault().post(mainBean)
            }
            else -> {
                MineInfoActivity.open(requireActivity())
            }
        }
    }

    override fun initView() {
        BarUtils.addMarginTopEqualStatusBarHeight(flMainTaskBar)

        rvMainTaskBody.adapter = taskAdapter

        taskAdapter.setOnItemChildClickListener { adapter, view, position ->
            val taskDay: TaskDay = taskAdapter.getItem(position)
            when (view.id) {
                R.id.tvTaskDayCompleteWait -> {
                    //状态 1=去完成,2=待领取,3=已完成
                    viewModel.taskFinish(taskDay.id)
                }
                R.id.tvTaskDayCompleteWith -> {
                    taskDayCompleteWith(taskDay)
                }
                R.id.ivTaskDayIcon -> {
                    if (taskDay.status == 1) {
                        taskDayCompleteWith(taskDay)
                    } else if (taskDay.status == 2) {
                        viewModel.taskFinish(taskDay.id)
                    }
                }
            }
        }

        ivMainTaskLucky.setOnClickListener {
            TaskGridActivity.open(requireActivity())
        }
        ivMainTaskInvite.setOnClickListener {
            TaskInviteActivity.open(requireActivity())
        }
        ivMainTaskFlop.setOnClickListener {
            TaskFlopActivity.open(requireActivity())
        }
    }

    override fun initData() {
        viewModel.taskDayList()
    }

    override fun onResume() {
        super.onResume()
        viewModel.taskDayList()
    }

    override fun initViewMode() {
        viewModel.taskDayLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                taskAdapter.setNewInstance(it)
            }
        })

        viewModel.baseLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let {
                viewModel.taskDayList()
            }
        })

        viewModel.luckyReceiveLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                flopPopup.fillData(it).showPopupWindow()
                viewModel.videoNoReward(advertisementType = 3)
                viewModel.taskDayList()
            }
        })
        viewModel.videoNoRewardLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
            val codeId: String? = response.httpData?.data?.advertising_space
            if (cid == null) {

            } else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdCSJ(mActivity = requireActivity(), codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdYLH(mActivity = requireActivity(), codeId = codeId)
            }
        })

        viewModel.videoTypeLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
                ?: return@Observer
            val codeId: String? = response.httpData?.data?.advertising_space
            if (codeId == null) {
                toast("广告位ID为空")
            } else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdCSJ(mActivity = requireActivity(), codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadRewardVideoAdYLH(mActivity = requireActivity(), codeId = codeId)
            }
        })

        viewModel.videoEndLiveData.observe(viewLifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.let {
                flopPopup.fillData(it.data).showPopupWindow()
                viewModel.videoNoReward(advertisementType = 3)
                viewModel.taskDayList()
                if (viewModel.signPopup.isShowing){
                    viewModel.signPopup.dismiss()
                }
            }
        })

        viewModel.videoNoRewardLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status != Status.SUCCESS)
                return@Observer
            val cid: Int? = response.httpData?.data?.cid
            val codeId: String? = response.httpData?.data?.advertising_space
            if (cid == null) {

            } else if (cid == 1 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdCSJ(mActivity = requireActivity(), codeId = codeId)
            } else if (cid == 2 && !codeId.isNullOrEmpty()) {
                viewModel.loadNativeExpressAdYLH(mActivity = requireActivity(), codeId = codeId)
            }
        })

        viewModel.luckySignLiveData.observe(this as LifecycleOwner, Observer { response ->
            if (response.status == Status.FAILURE) {
                toast(response.throwable?.msg ?: "未知错误")
            }
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let {
                flopPopup.fillData(it).showPopupWindow()
                viewModel.videoNoReward(advertisementType = 3)
            }
        })

        viewModel.rewardVerifyAdLiveData.observe(
            this as LifecycleOwner,
            Observer { isRewardVerify ->
                if (!isRewardVerify)
                    return@Observer
                if (viewModel.isRewardVerifyAdSign) {
                    val taskSign: TaskSign = viewModel.taskSignLiveData.value?.httpData?.data
                        ?: return@Observer
                    val signId: Int = taskSign.list[taskSign.sign_num ?: 0].id
                    val videoLogId:String = viewModel.videoTypeLiveData.value?.httpData?.data?.video_log_id
                        ?: return@Observer
                    viewModel.taskSign(signId,videoLogId)
                    viewModel.isRewardVerifyAdSign = false
                } else {
                    viewModel.videoTypeLiveData.value?.httpData?.data?.let {
                        viewModel.videoEnd(it.video_log_id)
                    }
                }
            })

        viewModel.viewAdLiveData.observe(viewLifecycleOwner, Observer { view ->
            view?.let {
                flopPopup.fillViewAd(view)
            }
        })

        viewModel.otherUrlLiveData.observe(this, Observer { response ->
            if (response.status == Status.FAILURE)
                toast(response.throwable?.msg ?: "未知错误")
            if (response.status != Status.SUCCESS)
                return@Observer
            response.httpData?.data?.let { image ->
                if (image.url.isNullOrEmpty()) {
                    toast("分享图片地址为空")
                } else {
                    val isHttps: Boolean = image.url.substring(0, 5).contains("http") ||
                            image.url.substring(0, 5).contains("https")
                    RxHttp.get("${if (isHttps) "" else AppConstance.URL_IMAGE}${image.url}")
                        .asDownload("${getDiskCacheDirectoryImage(requireContext()).path}/task_share.png")
                        .subscribe({
                            requireActivity().runOnUiThread {
                                if (shareType == 1) {
                                    wxShareImage(it)
                                }
                                if (shareType == 2) {
                                    qqShareImage(requireActivity(), it)
                                }
                            }
                            viewModel.taskShare(shareType)
                        }, {
                            toast(it.msg)
                        })
                }
            }
        })
    }
}